package com.cookor.poi.modules.mx.schedule;

import com.alibaba.fastjson.JSONObject;
import com.cookor.poi.utils.HttpUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

//@Service
//@Lazy(false)
public class YiMeiSchedule {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private String accessToken = "1";

//    @Scheduled(cron = "*/5 * * * * ?")
    public void getData() throws Exception {

        String post = sendPostRequest("https://api.yimei.ai/apiConsole/hfive/recordList", accessToken, "page=1&pageSize=10");
        if(post.equals("401")){
            System.out.println("去获取token");
            String s1 = sendGetRequest("http://localhost:5000/getToken");
            String unescapedJsonStr = s1.replace("\\", "");
            unescapedJsonStr = unescapedJsonStr.substring(1, unescapedJsonStr.length() - 1);
            String access_token = JSONObject.parseObject(unescapedJsonStr).getString("access_token");
            System.out.println(access_token);
            accessToken = access_token;
            post = sendPostRequest("https://api.yimei.ai/apiConsole/hfive/recordList", accessToken, "page=1&pageSize=10");
        }
        System.out.println(post);
    }

    @Test
    public void test()throws Exception{
        getData();
    }

    public static String sendGetRequest(String sendUrl) {
        StringBuilder result = new StringBuilder();
        try {
            // 创建URL对象
            URL url = new URL(sendUrl); // 替换为你的目标URL
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            // 设置接收类型
            connection.setRequestProperty("Accept", "application/json");

            // 检查服务器响应代码
            if (connection.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            String output;
            while ((output = br.readLine()) != null) {
                result.append(output);
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static String sendPostRequest(String requestURL, String accessToken, String urlParameters) {
        try {
            // 创建URL对象
            URL url = new URL(requestURL);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 添加请求头，例如accessToken
            connection.setRequestProperty("Cookie", "access_token="+accessToken);
            // 设置内容类型
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 发送POST请求必须设置这两个属性
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 获取输出流并写入参数
            try (OutputStream os = connection.getOutputStream()) {
                os.write(urlParameters.getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

            // 检查响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 创建一个StringBuilder来累积响应内容
                StringBuilder response = new StringBuilder();
                // 使用try-with-resources语句自动关闭资源
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String inputLine;
                    // 逐行读取响应内容
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                }
                return response.toString();
                // 将累积的响应内容转换为字符串并输出
            } else {
                // 处理错误
                return String.valueOf(responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
